package com.qqs.distributed.config;

import com.qqs.distributed.annotation.EnableDistributedCache;
import com.qqs.distributed.cache.CacheHandler;
import com.qqs.distributed.cache.RedisCacheHandler;
import com.qqs.distributed.lock.LockHandlerFactory;
import com.qqs.distributed.lock.RedissonLockHandlerFactory;
import com.qqs.distributed.service.DogService;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;


@Configuration
@EnableDistributedCache
public class RedisConfiguration {
    @Bean
    public RedisTemplate redisTemplate() {
        StringRedisTemplate redisTemplate = new StringRedisTemplate();
        RedisStandaloneConfiguration configuration = new RedisStandaloneConfiguration();
        configuration.setHostName("192.168.32.88");
        configuration.setPort(6379);
        JedisConnectionFactory connectionFactory = new JedisConnectionFactory(configuration);
        redisTemplate.setConnectionFactory(connectionFactory);
        return redisTemplate;
    }

    @Bean
    public CacheHandler redisCacheHandler(RedisTemplate redisTemplate) {
        RedisCacheHandler cacheHandler = new RedisCacheHandler(redisTemplate);
        return cacheHandler;
    }

    @Bean
    public RedissonClient redissonClient() {
        Config config = new Config();
        config.useSingleServer()
                .setAddress("redis://192.168.32.88:6379");
        return Redisson.create(config);
    }

    @Bean
    public LockHandlerFactory redissonLockHandlerFactory(RedissonClient redissonClient) {
        RedissonLockHandlerFactory lockHandlerFactory = new RedissonLockHandlerFactory(redissonClient);
        return lockHandlerFactory;
    }

    @Bean
    public DogService dogService() {
        return new DogService();
    }
}
